package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送手机短信验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R sengMsg(@RequestBody User user, HttpSession session){
        //1、后台获取手机号【13399998888】
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            //2、随机生成六位数字验证码  RandomUtil
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            System.out.println(code);
            log.info("code:{}",code);
            //3、调用SMSUtils2,给该手机号发送相应的验证码短信

            //4、将该验证码存入到session中，使用手机号作为key，值就是验证码
            session.setAttribute(phone,code);
            return R.success("手机验证码短信发送成功");
        }
        return R.error("短信发送失败");
    }

    /**
     * 移动用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Map map, HttpSession session){
        //1、用户输入手机收到的验证码，点击登录
        //2、收到用户输入的手机号【13399998888】+验证码【666666】
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //3、和真实的验证码【在哪呢？从session中取验证码】进行比对  从Redis中获取
        Object codeInSession = session.getAttribute(phone);
        if (codeInSession != null && codeInSession.equals(code)) {
            //如果能够比对成功，说明登录成功
            //比对成功：验证码正确，登录成功
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if(user == null){
                //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                // 登录成功，将用户信息[id]存入到session中
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        // 比对失败：验证码错误，登录失败
        return R.error("登录失败");
    }

    /**
     * 移动端用户退出
     * @return
     */
    @PostMapping("/loginout")
    public R loginOut(HttpServletRequest request, HttpServletResponse response){
        //清空session
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        //清空cookie
        Cookie cookie = new Cookie("user", null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return R.success("退出成功");
    }
}
